/**
 * Created by jaliu on 2015/2/13.
 */

var adminUsers = mongoose.model('backoffice_adminusers');
var async = require('async');
var Community = mongoose.model('community');
var toolUtil = require('../../common/utils/toolUtil');
var Users = mongoose.model('user');
var mysqlUtil = require('../../common/utils/mysqlUtil');
var md5 = require('MD5');



/**
 * userService.js
 * 后台管理用户登录
 *author：chenjinzhuan
 * */

// opm2.0新增登录
exports.userLoginService = function (req, callback) {
    var userName = req.body.userName;
    var password = req.body.password;

    var userId = null;

    async.series([

        function(callbackInner) {

            var sql = "select * from sys_user where loginName = ? and passWord = ? and isValid = 1";
            mysqlUtil.query(sql, [userName, password],function (err, result) {

                if (result && result.length) {
                    userId = result[0].sysUserID;
                    req.session.account = {userID:userId, username:userName};
                }

                callbackInner(err, result);
            });

        },

        function (callbackInner) {

            var sql = "";

            if (userId && userName == 'admin') {
                sql = "select * from sys_menu where isValid = 1 order by parentID,menuOrder";
            } else {
                sql = "select * from sys_menu A " +
                "inner join sys_menuInRole B on A.sys_menuID = B.sysMenuID " +
                "inner join sys_userInRole C on B.roleID = C.roleID " +
                "where A.isValid and C.sysUserID = " + userId + " order by parentID,menuOrder";
            }

            mysqlUtil.query(sql, function (err, result) {
                callbackInner(err, result);
            });
        },


    ], callback);


};




// opm1.0
exports.adminUserLoginService = function (input, callback) {
    var loginId = input.loginId; 
    var password = input.password;
    adminUsers.find({'loginId': loginId, 'password': password, $and:[{role: {$ne: 'Guest'}},{role: {$ne: 'moderator'}}]} , callback);
};

exports.adminUserLoginServiceByModerator = function (input, callback) {
    var loginId = input.loginId;
    var password = input.password;
    var opt = {
        mobilePhone: loginId,
        userPassword: password,
        userRole:1
    };
    Users.findOne(opt, '_id userName frozenOrNot email mobilePhone birthDate userRole nickName communityWay age gender maritalStatus hasChildren images apartmentDetail hobbies community homeTown.country homeTown.province homeTown.city homeTown.county huanxinUserName appSetting userType speciality userPortrait job school authenticationStatus roomUnit roomNumber showUnit invitationCode invitedBy children dateCreated')
        .populate('userPortrait', 'portraitURL value').populate('community', '_id communityName communityAddress communityLogo unitSwitch').populate('homeTown.country', '_id name').populate('homeTown.province', '_id name').populate('homeTown.city', '_id name').populate('homeTown.county', '_id name').populate('hobbies', '_id value')
        .exec(callback);
};

exports.adminUserLoginServiceByUserId = function (input, callback) {
    var userId = input.userId;
    var opt = {
        _id:userId,
        userRole:1
    };
    Users.findOne(opt, '_id userName frozenOrNot email mobilePhone birthDate userRole nickName communityWay age gender maritalStatus hasChildren images apartmentDetail hobbies community homeTown.country homeTown.province homeTown.city homeTown.county huanxinUserName appSetting userType speciality userPortrait job school authenticationStatus roomUnit roomNumber showUnit invitationCode invitedBy children dateCreated')
        .populate('userPortrait', 'portraitURL value').populate('community', '_id communityName communityAddress communityLogo unitSwitch').populate('homeTown.country', '_id name').populate('homeTown.province', '_id name').populate('homeTown.city', '_id name').populate('homeTown.county', '_id name').populate('hobbies', '_id value')
        .exec(callback);
};

exports.adminUserCreateService = function (input, callback) {

    async.series([

        function (callbackInner) {

            var adminUser = new adminUsers();
            adminUser.loginId = input.loginId;
            adminUser.userName = input.userName;
            adminUser.password = input.password;
            adminUser.role = input.role;
            adminUser.communities = input.communities;
            adminUser.appuser = input.appuser;
            adminUser.save(callbackInner);
        },
        function (callbackInner) {
            var userRole =[];
            if(input.role == 'moderator'){
                userRole.push(1);
            }
            if(input.role == 'Property'){
                userRole.push(2);
            }

            if(input.appuser != null && input.appuser !=""){
                Users.update({_id: input.appuser}, {userRole:userRole},{ multi: true }).exec(callbackInner);
            }else{
                callbackInner();
            }
        }
    ], callback);

};

exports.adminUserDeleteService = function (loginId, callback) {
    adminUsers.findOneAndRemove({loginId: loginId}, callback);
};

exports.adminUserUpdateService = function (loginId, input, callback) {

    async.series([
        function (callbackInner) {
            adminUsers.findOne({loginId: loginId}, function (err, adminUser) {
                if(input.newPassword){
                    if(input.newPassword){
                        if(input.oldPassword != adminUser.password){
                            callback({errmsg:'原密码输入错误!'})
                        }
                    }else{
                        if(input.newPassword != input.newPassword2){
                            callback({errmsg:'新密码输入不相同!'})
                        }
                    }
                };

                if (adminUser.appuser != null && adminUser.appuser.huanxinUserName != null) {
                    async.series([
                        function (callback1) {
                            async.each(adminUser.communities, function (communityId, c1) {
                                Community.findOne({_id: communityId}, 'chatGroupId', function (err, result) {
                                    toolUtil.getAndCacheHuanXinToken(function (err, token) {
                                        var args = {
                                            data: {},
                                            headers: {
                                                "Content-Type": "application/json",
                                                "Authorization": "Bearer " + token
                                            }
                                        };
                                        restClient.delete("https://a1.easemob.com/66xiaoqu/" + huanxinEnv + "/chatgroups/" + result.chatGroupId + "/users/" + adminUser.appuser.huanxinUserName, args, function (data, response) {
                                            c1();
                                        })
                                    });
                                });
                            }, function (err) {
                                callback1();
                            })
                        },
                        function (callback1) {
                            async.each(input.communities, function (communityId, c1) {
                                Community.findOne({_id: communityId}, 'chatGroupId', function (err, result) {
                                    toolUtil.getAndCacheHuanXinToken(function (err, token) {
                                        var args = {
                                            data: {},
                                            headers: {
                                                "Content-Type": "application/json",
                                                "Authorization": "Bearer " + token
                                            }
                                        };
                                        restClient.post("https://a1.easemob.com/66xiaoqu/" + huanxinEnv + "/chatgroups/" + result.chatGroupId + "/users/" + adminUser.appuser.huanxinUserName, args, function (data, response) {
                                            c1();
                                        })
                                    });
                                });
                            }, function (err) {
                                callback1();
                            })
                        }
                    ], callbackInner)
                } else {
                    callbackInner();
                }
            }).populate('appuser', 'huanxinUserName')
        },
        function (callbackInner) {

            var body = {
                'userName': input.userName,
                'role': input.role,
                'communities': input.communities
            };
            if(input.newPassword){
                body.password  = input.newPassword;
            };

            if (input.appuser != null && input.appuser !="") {
                body.appuser = input.appuser;
            }else{
                body.appuser = null;
            };

            adminUsers.update({loginId: loginId},
                {
                    $set: body
                }, callbackInner);
        },
        function (callbackInner) {
            if(input.appuser != input.oldAppUser && input.oldAppUser != null && input.oldAppUser !=""){

                Users.update({_id: input.oldAppUser}, {userRole:[]},{ multi: true }).exec(callbackInner);

            }else{
                callbackInner();
            }
        },
        function (callbackInner) {

            var userRole =[];
            if(input.role == 'moderator'){
                userRole.push(1);
            }
            if(input.role == 'Property'){
                userRole.push(2);
            }
            if(input.appuser != null && input.appuser !=""){

                Users.update({_id: input.appuser}, {userRole:userRole},{ multi: true }).exec(callbackInner);
            }else{
                callbackInner();
            }
        }

    ], callback);
};

exports.adminUserFindById = function (loginId, callback) {
    adminUsers.findOne({loginId: loginId}, function (err, results) {
        if (results != null) {
            delete results._doc.password;
            callback(null, results);
        }
    }).populate("communities", 'communityName').populate("appuser", 'mobilePhone');
};

exports.adminUserFindByToken = function (token, callback) {
    adminUsers.findOne({_id: token}, function (err, results) {
        if (results != null) {
            callback(null, results);
        }
    }).populate("communities", 'communityName').populate("appuser", 'mobilePhone');
};

exports.adminUserListService = function (page, pageSize, input,callback) {

    var pageSize = Number(pageSize);
    var index = (Number(page) - 1) * pageSize;

    if(input.userName){
        input.userName  = new RegExp(input.userName);
    }

    async.series([
        function (callbackInner) {
            adminUsers.count(input, function (err, count) {
                callbackInner(err, Math.ceil(count / pageSize));
            });
        },
        function (callbackInner) {
            adminUsers.find(input).populate("appuser", 'mobilePhone').populate("communities", "_id communityName").sort('domain').skip(index).limit(pageSize).exec(callbackInner);
        }
    ], callback);
};

